import {Component, OnInit} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {NbDialogRef, NbDialogService} from "@nebular/theme";
import {ActivatedRoute} from "@angular/router";
import {DisableEditRender} from "../../utils/DisableEditRender";
import {AdminService} from "../../AdminService";
import {DocService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {ResponseLocationInfo} from "../../energy/api/model/responseLocationInfo";
import {ResponseBuildingInfo} from "../../energy/api/model/responseBuildingInfo";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './building-document.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    button {
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .margin {
      margin:10px;
    }
  `],
})
export class BuildingDocumentComponent implements OnInit{
  settings = {
    pager: {
      display: true,
      perPage: 20
    },
    hideSubHeader: true,
    actions: {
      columnTitle: '操作',
      add: false,
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      buildingId: {
        title: 'ID',
        type: 'number',
      },
      buildingNo: {
        title: '楼栋编号',
        type: 'string',
      },
      buildingName: {
        title: '楼栋名称',
        type: 'string',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
      unit:{
        title: '单元列表',
        editable: false ,
        type: 'html',
        editor:{
          type: 'custom',
          component: DisableEditRender
        }
      }
    },
  };
  source: DataDataSource;
  ld?:number=null;
  buildingNo:string ='';
  buildingName:string='';
  constructor(private service: SmartTableData
              ,private api:DocService
              ,private dialogService: NbDialogService
              ,private route: ActivatedRoute
              ,private admin:AdminService) {
  }
  ngOnInit(): void {
    this.route.paramMap.subscribe(value=>{
      const ld = value.get("ld");
      if(ld!=null) this.ld = Number(ld);
      this.source = new DataDataSource(this.api,this.ld);
    });

  }
  filter(){
    this.source.buildingName = this.buildingName;
    this.source.buildingNo = this.buildingNo;
    this.source.setPage(1);
    this.source.refresh();
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECASyncBuildingInfo(new BaseRequest([{
            operateType:"2",
            buildingId:event.data['buildingId']
      }])).toPromise().then(res=>{
        if(res.success){
          event.confirm.resolve();
        }else{
          event.confirm.reject();
        }
      }).catch(e=>{
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event):void {
    this.api.postECASyncBuildingInfo(new BaseRequest(
      [{
        operateType:"1",
        buildingId:event.data['buildingId'],
        buildingNo:event.newData['buildingNo'],
        buildingName:event.newData['buildingName'],
        extInfo:event.newData['extInfo'],
      }]
    )).toPromise().then(response=>{
        console.log(response);
        event.confirm.resolve();
    }).catch(e=>{
      console.log(e);
      event.confirm.reject();
    })
  }

  openAddPrompt(){
    this.dialogService.open(BuildingAddPrompt)
      .onClose.subscribe(v=>{
      if(v==null) return;
      this.api.postECASyncBuildingInfo(new BaseRequest(
        [
          {
            operateType:"0",
            locationId:Number(v['locationId']),
            buildingNo:v['buildingNo'],
            buildingName:v['buildingName'],
            extInfo:v['extInfo'],
          }
        ]
      )).toPromise().then(response=>{
        console.log(response);
        this.source.refresh();
      })
    });
  }

}


export class DataDataSource extends LocalDataSource {
  buildingName:string = '';
  buildingNo:string = '';
  all: number = -1;
  constructor(private api: DocService,private locationId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      locationId:this.locationId
    };
    if(this.buildingNo!='') query['buildingNo'] = this.buildingNo;
    if(this.buildingName!='') query['buildingName'] = this.buildingName;
    return this.api.requestBuildingInfo(new BaseRequest(query)).pipe(map((res:ResponseBuildingInfo)=>{
      this.all = res.dataCount;
      return res.data.map(value=>{
        value['unit'] = `<a href="/#/pages/doc/ud/bd/${value.buildingId}">查看单元</a>`;
        return value;
      });
    })).toPromise();
  }
}
@Component({
  selector: 'building-add-prompt',
  template:`
    <nb-card>
      <nb-card-header>新建楼栋</nb-card-header>
      <nb-card-body>
        <div><input #locationId nbInput placeholder="地址ID"></div>
        <div><input #buildingNo nbInput placeholder="楼栋编号"></div>
        <div><input #buildingName nbInput placeholder="楼栋名称"></div>
        <div><input #extInfo nbInput placeholder="额外信息"></div>
      </nb-card-body>
      <nb-card-footer>
        <button nbButton status="danger" (click)="cancel()">Cancel</button>
        <button nbButton status="success" (click)="submit({'locationId':locationId.value,'buildingNo':buildingNo.value,'buildingName':buildingName.value,'extInfo':extInfo.value})">Submit</button>
      </nb-card-footer>
    </nb-card>
  `
})
export class BuildingAddPrompt{
  constructor(protected ref: NbDialogRef<BuildingAddPrompt>) {}

  cancel() {
    this.ref.close();
  }

  submit(result) {
    this.ref.close(result);
  }
}
